﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NinjaParser
{
	internal enum ParserState
	{
		Outside, Inside, Quote
	}

	public class StringTokenizer
	{
		private string inputLine;
		LinkedList<string> ret = new LinkedList<string>();
		StringBuilder builder = new StringBuilder();

		public StringTokenizer(string line)
		{
			inputLine = line;
		}

		private void Push(string value)
		{
			ret.AddLast(value.Trim());
			builder = new StringBuilder();
		}

		public LinkedList<string> Parse()
		{
			ParserState state = ParserState.Outside;

			foreach (Char c in inputLine)
			{
				if (char.IsControl(c))
					continue;

				switch (state)
				{
					case ParserState.Outside:
						#region Outside

						if (Char.IsWhiteSpace(c))
							continue;
						else if (c == ',')
						{
							 Push(",");
						}
						else if (c == '"')
							state = ParserState.Quote;
						else
						{
							builder.Append(c);
							state = ParserState.Inside;
						}

						break;
						#endregion
							
					case ParserState.Inside:
						#region Inside
						if(Char.IsWhiteSpace(c))
						{
							Push(builder.ToString());
							state = ParserState.Outside;
						}
						else if (c == ',')
						{
							state = ParserState.Outside;
							Push(builder.ToString());
							Push(",");
						}
						else if (c == '"')
							state = ParserState.Quote;
						else
							builder.Append(c);
						break;
						#endregion

					case ParserState.Quote:
						#region Quote

						if (c == '"')
						{
							state = ParserState.Outside;
							Push(builder.ToString());
						}
						else
							builder.Append(c);
						break;


						break;
						#endregion

				}
			}

			if(state == ParserState.Quote)
			{
				throw new Exception("Unmatched quote found.");
			}
			else if (state == ParserState.Inside)
			{
				Push(builder.ToString());
			}

			return ret;
		}
	}
}